package com.wenjun.young.config;

import cn.org.atool.fluent.mybatis.spring.MapperFactory;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author caowenjun
 */
@Configuration
@MapperScan(basePackages = {"com.wenjun.young.web.mapper","com.wenjun.young.web.dao"}, sqlSessionFactoryRef = "sqlSessionFactory")
public class DataSourceConfiguration {

	@Primary
	@Bean(name = "dataSource")
	@ConfigurationProperties("spring.datasource.druid")
	public DataSource dataSource() {
		return DruidDataSourceBuilder.create().build();
	}

	@Bean(name = "transactionManager")
	@Primary
	public DataSourceTransactionManager mainTransactionManager(@Qualifier("dataSource") DataSource mainDataSource) {
		return new DataSourceTransactionManager(mainDataSource);
	}

	@Bean(name = "sqlSessionFactory")
	@Primary
	public SqlSessionFactory mainSqlSessionFactory(@Qualifier("dataSource") DataSource mainDataSource)
			throws Exception {
		SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
		sessionFactory.setDataSource(mainDataSource);
		sessionFactory.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
		return sessionFactory.getObject();
	}

	@Bean
	public MapperFactory mapperFactory() {
		return new MapperFactory();
	}
}
